import os
import json
import getpass

from PySide2.QtWidgets import *
from PySide2.QtCore import Qt, QSize
from PySide2.QtGui import QPixmap

from main_win import MainWin
from CustWidgets import CreateDataStreamDialog
from CustWidgets import OpenDataStreamDialog
from CustWidgets import PasswordDialog
from CustStyleSheets import *

welcome_text = \
"""
<html><head/><body>
    <p align=\"center\">Welcome to the Edge Insights for Industrial (EII) Deployment Tool.</p>
    <p align=\"center\">This tool will guide you through the process of configuring, testing,</p>
    <p align=\"center\">deploying your application for your project.</p>
</body></html>
"""


class WelcomeWin(QWidget):
    
    def __init__(self, root_win=None, parent=None):
        super(WelcomeWin, self).__init__(parent=parent)
        self.root_win = root_win
        
        self.init_ui()
        self.signals_collector()
    
    def init_ui(self):
        self.grid_lyt_global = QGridLayout(self)
        
        self.lbl_logo = QLabel(self)
        self.lbl_logo.setPixmap(QPixmap("./images/logo.png"))
        self.lbl_logo.setAlignment(Qt.AlignCenter)
        self.grid_lyt_global.addWidget(self.lbl_logo, 1, 0, 1, 1)
        
        self.lbl_welcome_text = QLabel(self)
        self.lbl_welcome_text.setText(welcome_text)
        self.grid_lyt_global.addWidget(self.lbl_welcome_text, 3, 0, 1, 1)
        
        self.btn_create_new = QPushButton(self)
        self.btn_create_new.setText("Create New Data Stream")
        self.btn_create_new.setMinimumSize(QSize(300, 30))
        self.btn_create_new.setMaximumSize(QSize(300, 30))
        self.grid_lyt_global.addWidget(self.btn_create_new, 5, 0, 1, 1, Qt.AlignHCenter)
        
        self.btn_open_existing = QPushButton(self)
        self.btn_open_existing.setText("Open Existing Data Stream")
        self.btn_open_existing.setMinimumSize(QSize(300, 30))
        self.btn_open_existing.setMaximumSize(QSize(300, 30))
        self.grid_lyt_global.addWidget(self.btn_open_existing, 7, 0, 1, 1, Qt.AlignHCenter)
        
        self.btn_deploy_existing = QPushButton(self)
        self.btn_deploy_existing.setText("Deploy Existing Data Streams")
        self.btn_deploy_existing.setMinimumSize(QSize(300, 30))
        self.btn_deploy_existing.setMaximumSize(QSize(300, 30))
        self.grid_lyt_global.addWidget(self.btn_deploy_existing, 9, 0, 1, 1, Qt.AlignHCenter)

        # Spacers
        spacer1 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.grid_lyt_global.addItem(spacer1, 0, 0, 1, 1)
        spacer2 = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.grid_lyt_global.addItem(spacer2, 2, 0, 1, 1)
        spacer3 = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.grid_lyt_global.addItem(spacer3, 4, 0, 1, 1)
        spacer4 = QSpacerItem(20, 15, QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.grid_lyt_global.addItem(spacer4, 6, 0, 1, 1)
        spacer5 = QSpacerItem(20, 15, QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.grid_lyt_global.addItem(spacer5, 8, 0, 1, 1)
        spacer6 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.grid_lyt_global.addItem(spacer6, 10, 0, 1, 1)

    def slot_create_new(self):
        cfg = {}
        dialog = CreateDataStreamDialog(cfg)
        dialog.show()
        dialog.exec_()
        if not cfg:
            return

        # Remove the older one
        win_main_old = self.root_win.grid_lyt_global.itemAtPosition(1, 0)
        if win_main_old:
            self.root_win.grid_lyt_global.removeItem(win_main_old)
            # win_main_old.widget().deleteLater()
            win_main_old = None
        
        # Create a new one
        win_main = MainWin(
            root_win=self.root_win,
            welcome_win=self,
            eii_home=cfg["eii_home"], 
            data_stream_name=cfg["project_name"], 
            pwd=cfg["host_pwd"]
        )
        self.root_win.grid_lyt_global.addWidget(win_main, 1, 0, 1, 1)
        
        # Hide welcome-window and show main-window
        self.hide()
        win_main.show()

    def slot_open_existing(self):
        # Check whether EII Home Path is set
        cur_user = getpass.getuser()
        eii_dep_tool_cfg_file = os.path.join("/home/{}/.eii".format(cur_user), "eii_deploy_tool.cfg")
        if not os.path.exists(eii_dep_tool_cfg_file):
            self._show_msg_dialog("\"EII Home Path\" is not set yet, please create new data stream.")
            return

        # Get eii deploy workspace
        with open(eii_dep_tool_cfg_file, "r") as f:
            content = f.read()
            if content:
                # Validate the content
                content_dict = json.loads(content)
                eii_home = content_dict["eii_home"]
                eii_helper_workspace = os.path.join(eii_home, "eii_helper", "workspace")
                if not os.path.exists(eii_helper_workspace) or not os.listdir(eii_helper_workspace):
                    self._show_msg_dialog("No existing data stream was found, please create a new one.")
                    return
                
                # Show open data stream ui
                cfg = {}
                dialog = OpenDataStreamDialog(eii_home=eii_home, config=cfg)
                dialog.show()
                dialog.exec_()
                if not cfg:
                    return
            else:
                self._show_msg_dialog("Invalid eii deploy tool config file, please reset it.")
                return

        # Remove the older one
        win_main_old = self.root_win.grid_lyt_global.itemAtPosition(1, 0)
        if win_main_old:
            self.root_win.grid_lyt_global.removeItem(win_main_old)
            # win_main_old.widget().deleteLater()
            win_main_old = None
        
        # Create a new one
        win_main = MainWin(
            root_win=self.root_win,
            welcome_win=self,
            eii_home=cfg["eii_home"], 
            data_stream_name=cfg["project_name"], 
            pwd=cfg["host_pwd"]
        )
        self.root_win.grid_lyt_global.addWidget(win_main, 1, 0, 1, 1)
        
        # Hide welcome-window and show main-window
        self.hide()
        win_main.show()

    def slot_deploy_existing(self):

        # Get user password
        tmp = {}
        pwd_dialog = PasswordDialog(config=tmp)
        pwd_dialog.show()
        pwd_dialog.exec_()
        if "pwd" not in tmp.keys():
            return
        pwd = tmp["pwd"]

        # Check whether EII Home Path is set
        cur_user = getpass.getuser()
        eii_dep_tool_cfg_file = os.path.join("/home/{}/.eii".format(cur_user), "eii_deploy_tool.cfg")
        if not os.path.exists(eii_dep_tool_cfg_file):
            self._show_msg_dialog("\"EII Home Path\" is not set yet, please create new data stream.")
            return

        # Get eii deploy workspace
        with open(eii_dep_tool_cfg_file, "r") as f:
            content = f.read()
            if content:
                # Validate the content
                content_dict = json.loads(content)
                eii_home = content_dict["eii_home"]
                eii_helper_workspace = os.path.join(eii_home, "eii_helper", "workspace")
                if not os.path.exists(eii_helper_workspace) or not os.listdir(eii_helper_workspace):
                    self._show_msg_dialog("No existing data stream was found, please create a new one.")
                    return
            else:
                self._show_msg_dialog("Invalid eii deploy tool config file, please reset it.")
                return

        # Remove the older one
        win_main_old = self.root_win.grid_lyt_global.itemAtPosition(1, 0)
        if win_main_old:
            self.root_win.grid_lyt_global.removeItem(win_main_old)
            # win_main_old.widget().deleteLater()
            win_main_old = None
        
        # Create a new one
        win_main = MainWin(
            root_win=self.root_win,
            welcome_win=self,
            eii_home=eii_home, 
            data_stream_name="", 
            pwd=pwd,
            show_all=False,
            current_win="deploy"
        )
        # Show deploy-window
        win_main.wgt_config.hide()
        win_main.wgt_test.hide()
        win_main.wgt_deploy.show()
        # Update bottom buttons' status
        win_main.btn_prev.setStyleSheet(SS_MINI_BTN_DISABLE)
        win_main.btn_next.setStyleSheet(SS_MINI_BTN_DISABLE)
        # Update top labels' status
        win_main.lbl_config.setStyleSheet(SS_LBL_DEACTIVATED)
        win_main.lbl_test.setStyleSheet(SS_LBL_DEACTIVATED)
        win_main.lbl_deploy.setStyleSheet(SS_LBL_ACTIVATED)
        self.root_win.grid_lyt_global.addWidget(win_main, 1, 0, 1, 1)
        
        # Hide welcome-window and show main-window
        self.hide()
        win_main.show()

    def signals_collector(self):
        self.btn_create_new.clicked.connect(self.slot_create_new)
        self.btn_open_existing.clicked.connect(self.slot_open_existing)
        self.btn_deploy_existing.clicked.connect(self.slot_deploy_existing)

    def _show_msg_dialog(self, text):
        QMessageBox.warning(self, "Warning", "{}".format(text), QMessageBox.Ok)
